﻿using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;

namespace Util
{
    public class MacHelper
    {
        /// <summary>
        /// 获取电脑 MAC（物理） 地址
        /// </summary>
        /// <returns></returns>
        public static string GetMacAddress()
        {
            //本地计算机网络连接信息
            IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
            //获取本机所有网络连接
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            //获取本机电脑名
            var HostName = computerProperties.HostName;
            //获取域名
            var DomainName = computerProperties.DomainName;
            if (nics == null || nics.Length < 1)
                return "";
            var MACIp = "";
            foreach (NetworkInterface adapter in nics)
            {
                if(adapter.OperationalStatus!= OperationalStatus.Up)
                    continue;
                var adapterName = adapter.Name;
                var adapterDescription = adapter.Description;
                var NetworkInterfaceType = adapter.NetworkInterfaceType;
                if (adapterName.Contains("以太网"))
                {
                    PhysicalAddress address = adapter.GetPhysicalAddress();
                    byte[] bytes = address.GetAddressBytes();
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        MACIp += bytes[i].ToString("X2");

                        if (i != bytes.Length - 1)
                        {
                            MACIp += "-";
                        }
                    }
                }
            }
            return MACIp;
        }
    }
}
